/*
 * @Descripttion: 工具集
 * @version: 1.1
 * @LastEditors: sakuya
 * @LastEditTime: 2021年7月20日10:58:41
 */

import CryptoJS from 'crypto-js';
import dayjs from 'dayjs';
import to from 'await-to-js';

const tool = {}

/* localStorage */
tool.data = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return localStorage.setItem(table, _set);
	},
	get(table) {
		var data = localStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return localStorage.removeItem(table);
	},
	clear() {
		return localStorage.clear();
	},
	setToken(token) {
		return this.set('TOKEN', token);
	},
	getToken() {
		return this.get('TOKEN') || '';
	},
	setMenu(menu) {
		return this.set('MENU', menu);
	},
	getMenu() {
		return this.get('MENU') || [];
	},
	setUserInfo(userInfo) {
		return this.set('USER_INFO', userInfo);
	},
	getUserInfo() {
		return this.get('USER_INFO') || {};
	},
	getPermissions() {
		return this.get('PERMISSIONS') || [];
	},
	setPermissions(permissions) {
		return this.set('PERMISSIONS', permissions);
	}
}

/*sessionStorage*/
tool.session = {
	set(table, settings) {
		var _set = JSON.stringify(settings)
		return sessionStorage.setItem(table, _set);
	},
	get(table) {
		var data = sessionStorage.getItem(table);
		try {
			data = JSON.parse(data)
		} catch (err) {
			return null
		}
		return data;
	},
	remove(table) {
		return sessionStorage.removeItem(table);
	},
	clear() {
		return sessionStorage.clear();
	}
}

/* Fullscreen */
tool.screen = function (element) {
	var isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
	if (isFull) {
		if (document.exitFullscreen) {
			document.exitFullscreen();
		} else if (document.msExitFullscreen) {
			document.msExitFullscreen();
		} else if (document.mozCancelFullScreen) {
			document.mozCancelFullScreen();
		} else if (document.webkitExitFullscreen) {
			document.webkitExitFullscreen();
		}
	} else {
		if (element.requestFullscreen) {
			element.requestFullscreen();
		} else if (element.msRequestFullscreen) {
			element.msRequestFullscreen();
		} else if (element.mozRequestFullScreen) {
			element.mozRequestFullScreen();
		} else if (element.webkitRequestFullscreen) {
			element.webkitRequestFullscreen();
		}
	}
}

/* 复制对象 */
tool.objCopy = function (obj) {
	return JSON.parse(JSON.stringify(obj));
}

/* 日期格式化 */
tool.dateFormat = function (date, fmt = 'yyyy-MM-dd hh:mm:ss') {
	date = new Date(date)
	var o = {
		"M+": date.getMonth() + 1,                 //月份
		"d+": date.getDate(),                    //日
		"h+": date.getHours(),                   //小时
		"m+": date.getMinutes(),                 //分
		"s+": date.getSeconds(),                 //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds()             //毫秒
	};
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
}

tool.timeToDate = function (time,format = 'YYYY-MM-DD HH:mm:ss') {
	return dayjs(time).format(format)
}

/* 千分符 */
tool.groupSeparator = function (num) {
	num = num + '';
	if (!num.includes('.')) {
		num += '.'
	}
	return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
		return $1 + ',';
	}).replace(/\.$/, '');
}

/* 常用加解密 */
tool.crypto = {
	//MD5加密
	MD5(data) {
		return CryptoJS.MD5(data).toString()
	},
	//BASE64加解密
	BASE64: {
		encrypt(data) {
			return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
		},
		decrypt(cipher) {
			return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8)
		}
	},
	//AES加解密
	AES: {
		encrypt(data, secretKey) {
			const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			})
			return result.toString()
		},
		decrypt(cipher, secretKey) {
			const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			})
			return CryptoJS.enc.Utf8.stringify(result);
		}
	}
}

tool.isArray = function (value) {
	if (typeof Array.isArray === "function") {
		return Array.isArray(value);
	} else {
		return Object.prototype.toString.call(value) === "[object Array]";
	}
}

tool.isObject = function (value) {
	return Object.prototype.toString.call(value) === "[object Object]";
}

tool.isNumber = function (value) {
	return !isNaN(Number(value));
}

tool.isFunction = function (value) {
	return typeof value == "function";
}

tool.isString = function (value) {
	return typeof value == "string";
}

tool.isEmpty = function (value) {
	if (tool.isArray(value)) {
		return value.length === 0;
	}

	if (tool.isObject(value)) {
		return Object.keys(value).length === 0;
	}

	return value === "" || value === undefined || value === null;
}
// 地址反转
tool.revisePath = function (path) {
	if (!path) {
		return "";
	}

	if (path[0] == "/") {
		return path;
	} else {
		return `/${path}`;
	}
};
// 排序
tool.orderBy = function (list, key) {
	return list.sort((a, b) => a[key] - b[key]);
}
// 数组转树
tool.deepTree = function (list, parentIdName = "parentId", idName = "id", childrenName = "children") {
	if (!tool.isArray(list)) {
		return [];
	}
	let newList = [];
	let map = {};

	list.forEach((e) => (map[e[idName]] = e));

	list.forEach((e) => {
		const parent = map[e[parentIdName]];

		if (parent) {
			(parent[childrenName] || (parent[childrenName] = [])).push(e);
		} else {
			newList.push(e);
		}
	});

	const fn = (list) => {
		list.map((e) => {
			if (e[childrenName] instanceof Array) {
				e[childrenName] = tool.orderBy(e[childrenName], "orderNum");

				fn(e[childrenName]);
			}
		});
	};

	fn(newList);

	return tool.orderBy(newList, "orderNum");
}
tool.deepTreeOrder = function (list, parentIdName = "parentId", idName = "id",
							   childrenName = "children",orderFn = (a,b)=>a.orderNum-b.orderNum) {
	if (!tool.isArray(list)) {
		return [];
	}
	let newList = [];
	let map = {};

	list.forEach((e) => (map[e[idName]] = e));

	list.forEach((e) => {
		const parent = map[e[parentIdName]];

		if (parent) {
			(parent[childrenName] || (parent[childrenName] = [])).push(e);
		} else {
			newList.push(e);
		}
	});

	const fn = (list) => {
		list.map((e) => {
			if (e[childrenName] instanceof Array) {
				e[childrenName] = e[childrenName].sort(orderFn);

				fn(e[childrenName]);
			}
		});
	};

	fn(newList);

	return newList.sort(orderFn);
}
// 树转数组
tool.revDeepTree = function (list = [], parentIdName = "parentId") {
	let d = [];
	let id = 0;

	const deep = (list, parentId) => {
		list.forEach((e) => {
			if (!e.id) {
				e.id = id++;
			}

			e[parentIdName] = parentId;

			d.push(e);

			if (e.children && tool.isArray(e.children)) {
				deep(e.children, e.id);
			}
		});
	};

	deep(list || [], null);

	return d;
}
// 驼峰转中横线 AaBbCc 转 aa-bb-cc
tool.camelCaseToHyphen = function (str) {
	return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
// 中横线转 驼峰 aa-bb-cc 转 aaBbCc
tool.transformStr3 = function (str) {
	var re = /-(\w)/g;
	return str.replace(re, function ($0, $1) {
		return $1.toUpperCase();
	});
}
// 去除前后字符串
tool.trim = function (str, char) {
	if (!str) {
		return "";
	}

	if (!char) {
		return str.replace(/^\s+|\s+$/g, "");
	}

	return str.replace(new RegExp("^" + char + "*"), "").replace(new RegExp(char + "*$"), "");
}
// 转换为组件名称
tool.transformName = function (str) {
	return tool.trim(str,'/').replaceAll('/', "-");
}
// 获取我的菜单
tool.adminGetMyMenu = async function (apiObj) {
	var [err,menu] = await to(apiObj.system.admin.permMenu())
	if(err){
		return [false,err.message]
	}
	// var menu = {"code":0,"message":"成功","version":"1.0.0","data":{"menus":[{"create_at":0,"delete_at":0,"icon":"ht-icon-dashboard-line","id":1,"is_show":1,"keep_alive":1,"name":"工作台","parent_id":0,"perms":"","router":"","sort":10,"type":0,"update_at":1650251979,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-system","id":2,"is_show":1,"keep_alive":1,"name":"系统","parent_id":0,"perms":"","router":"","sort":20,"type":0,"update_at":1650213752,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-menu","id":8,"is_show":1,"keep_alive":1,"name":"菜单列表","parent_id":27,"perms":"","router":"/system/menu","sort":2,"type":1,"update_at":1650262485,"view_path":"system/menu"},{"create_at":0,"delete_at":0,"icon":"sc-icon-user","id":27,"is_show":1,"keep_alive":0,"name":"管理员管理","parent_id":2,"perms":"","router":"","sort":1,"type":0,"update_at":1650213811,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-log","id":29,"is_show":1,"keep_alive":1,"name":"请求日志","parent_id":105,"perms":"","router":"/gdshop/log","sort":1,"type":1,"update_at":1652948261,"view_path":"setting/log"},{"create_at":0,"delete_at":0,"icon":"sc-icon-favor","id":43,"is_show":1,"keep_alive":1,"name":"crud 示例","parent_id":45,"perms":"","router":"/crud","sort":1,"type":1,"update_at":0,"view_path":"cool/modules/demo/views/crud.vue"},{"create_at":0,"delete_at":0,"icon":"sc-icon-common","id":45,"is_show":0,"keep_alive":1,"name":"组件库","parent_id":1,"perms":"","router":"","sort":2,"type":0,"update_at":1650251986,"view_path":""},{"create_at":0,"delete_at":0,"icon":"icon-favor","id":49,"is_show":1,"keep_alive":1,"name":"quill 富文本编辑器","parent_id":45,"perms":"","router":"/editor-quill","sort":2,"type":1,"update_at":0,"view_path":"cool/modules/demo/views/editor-quill.vue"},{"create_at":0,"delete_at":0,"icon":"sc-icon-common","id":78,"is_show":1,"keep_alive":1,"name":"参数配置","parent_id":2,"perms":"","router":"","sort":4,"type":0,"update_at":1650213845,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-menu","id":79,"is_show":1,"keep_alive":1,"name":"参数列表","parent_id":78,"perms":"","router":"/gdshop/configs","sort":0,"type":1,"update_at":1652942877,"view_path":"setting/configs"},{"create_at":0,"delete_at":0,"icon":"sc-icon-favor","id":86,"is_show":1,"keep_alive":1,"name":"文件上传","parent_id":45,"perms":"","router":"/upload","sort":3,"type":1,"update_at":0,"view_path":"cool/modules/demo/views/upload.vue"},{"create_at":0,"delete_at":0,"icon":"sc-icon-rank","id":105,"is_show":1,"keep_alive":1,"name":"监控管理","parent_id":2,"perms":"","router":"","sort":6,"type":0,"update_at":1650213855,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-user","id":122,"is_show":1,"keep_alive":1,"name":"会员","parent_id":0,"perms":"","router":"","sort":30,"type":0,"update_at":1650252017,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-user","id":123,"is_show":1,"keep_alive":1,"name":"会员管理","parent_id":122,"perms":"","router":"/member/manage","sort":0,"type":1,"update_at":1652841783,"view_path":"member/manage.vue"},{"create_at":0,"delete_at":0,"icon":"sc-icon-cms","id":130,"is_show":1,"keep_alive":1,"name":"CMS","parent_id":0,"perms":"","router":"","sort":40,"type":0,"update_at":1650270127,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-article","id":132,"is_show":1,"keep_alive":1,"name":"文章","parent_id":130,"perms":"","router":"/cms/article","sort":0,"type":1,"update_at":1650273319,"view_path":"cms/article"},{"create_at":0,"delete_at":0,"icon":"sc-icon-slide","id":133,"is_show":1,"keep_alive":1,"name":"幻灯片","parent_id":130,"perms":"","router":"/cms/slides","sort":0,"type":1,"update_at":1650295664,"view_path":"cms/slides"},{"create_at":0,"delete_at":0,"icon":"sc-icon-link","id":134,"is_show":1,"keep_alive":1,"name":"友情链接","parent_id":130,"perms":"","router":"/cms/links","sort":0,"type":1,"update_at":1650295636,"view_path":"cms/links"},{"create_at":0,"delete_at":0,"icon":"sc-icon-shop","id":135,"is_show":1,"keep_alive":1,"name":"商城","parent_id":0,"perms":"","router":"","sort":50,"type":0,"update_at":1650252026,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-shop2","id":137,"is_show":0,"keep_alive":1,"name":"店铺","parent_id":135,"perms":"","router":"/shop/store","sort":50,"type":1,"update_at":1650378499,"view_path":"cool/modules/shop/views/store.vue"},{"create_at":0,"delete_at":0,"icon":"sc-icon-goods2","id":138,"is_show":1,"keep_alive":1,"name":"商品管理","parent_id":210,"perms":"","router":"/shop/goods","sort":60,"type":1,"update_at":1650380323,"view_path":"shop/goods"},{"create_at":0,"delete_at":0,"icon":"sc-icon-order","id":139,"is_show":1,"keep_alive":1,"name":"订单","parent_id":135,"perms":"","router":"/shop/order","sort":70,"type":1,"update_at":1651073478,"view_path":"shop/order"},{"create_at":0,"delete_at":0,"icon":"sc-icon-discount","id":140,"is_show":1,"keep_alive":1,"name":"营销","parent_id":0,"perms":"","router":"","sort":90,"type":0,"update_at":1650252036,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-aftersales","id":141,"is_show":1,"keep_alive":1,"name":"售后","parent_id":135,"perms":"","router":"/shop/orderRefund","sort":80,"type":1,"update_at":1652239808,"view_path":"shop/orderRefund"},{"create_at":0,"delete_at":0,"icon":"sc-icon-classify","id":162,"is_show":1,"keep_alive":1,"name":"CMS分类","parent_id":130,"perms":"","router":"/cms/category","sort":0,"type":1,"update_at":1650375387,"view_path":"cms/category"},{"create_at":1620144664,"delete_at":0,"icon":"sc-icon-common","id":167,"is_show":1,"keep_alive":1,"name":"角色列表","parent_id":27,"perms":"","router":"/system/role","sort":0,"type":1,"update_at":1650262336,"view_path":"system/role"},{"create_at":1620285573,"delete_at":0,"icon":"sc-icon-user","id":168,"is_show":1,"keep_alive":1,"name":"管理员列表","parent_id":27,"perms":"","router":"/system/admin","sort":0,"type":1,"update_at":1650262130,"view_path":"system/admin"},{"create_at":1620286616,"delete_at":0,"icon":"","id":169,"is_show":0,"keep_alive":0,"name":"通用","parent_id":0,"perms":"","router":"","sort":9999,"type":0,"update_at":1649811203,"view_path":""},{"create_at":1620286648,"delete_at":0,"icon":"sc-icon-user","id":170,"is_show":1,"keep_alive":1,"name":"个人中心","parent_id":169,"perms":"","router":"/myinfo","sort":0,"type":1,"update_at":0,"view_path":"cool/modules/gdshop/views/myinfo.vue"},{"create_at":1622100184,"delete_at":0,"icon":"","id":188,"is_show":0,"keep_alive":0,"name":"文件空间","parent_id":169,"perms":"","router":"","sort":0,"type":1,"update_at":0,"view_path":""},{"create_at":1622191779,"delete_at":0,"icon":"sc-icon-classify","id":191,"is_show":1,"keep_alive":1,"name":"商品分类","parent_id":135,"perms":"","router":"/shop/category","sort":10,"type":1,"update_at":1650377600,"view_path":"shop/category"},{"create_at":1625304624,"delete_at":0,"icon":"sc-icon-zhuangxiu","id":192,"is_show":1,"keep_alive":1,"name":"装修页面","parent_id":135,"perms":"","router":"/shop/diyPage","sort":9000,"type":1,"update_at":1650380444,"view_path":"shop/diyPage"},{"create_at":1625996997,"delete_at":0,"icon":"sc-icon-coupon","id":193,"is_show":1,"keep_alive":1,"name":"优惠券","parent_id":140,"perms":"","router":"/marketing/coupon","sort":10,"type":1,"update_at":1653034133,"view_path":"marketing/coupon"},{"create_at":1625997022,"delete_at":0,"icon":"sc-icon-tuan","id":194,"is_show":1,"keep_alive":1,"name":"拼团","parent_id":140,"perms":"","router":"","sort":20,"type":0,"update_at":1666190225,"view_path":""},{"create_at":1625997090,"delete_at":0,"icon":"sc-icon-miaosha","id":195,"is_show":1,"keep_alive":1,"name":"秒杀","parent_id":140,"perms":"","router":"","sort":30,"type":0,"update_at":1666193771,"view_path":""},{"create_at":1625997117,"delete_at":0,"icon":"sc-icon-choujiang","id":196,"is_show":0,"keep_alive":1,"name":"抽奖","parent_id":140,"perms":"","router":"","sort":40,"type":1,"update_at":1645853222,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-menu-brand","id":197,"is_show":0,"keep_alive":1,"name":"品牌","parent_id":135,"perms":"","router":"/shop/brand","sort":20,"type":1,"update_at":1650378493,"view_path":""},{"create_at":0,"delete_at":0,"icon":"","id":198,"is_show":0,"keep_alive":0,"name":"设计页面","parent_id":135,"perms":"","router":"/shop/diyPage/itemList","sort":9999,"type":1,"update_at":1652342848,"view_path":"shop/diyPage/itemList"},{"create_at":0,"delete_at":0,"icon":"sc-icon-zhe","id":199,"is_show":1,"keep_alive":1,"name":"满减满折","parent_id":212,"perms":"","router":"/marketing/discountActivity","sort":11,"type":1,"update_at":1653034127,"view_path":"marketing/discountActivity"},{"create_at":0,"delete_at":0,"icon":"sc-icon-activity2","id":200,"is_show":0,"keep_alive":1,"name":"买送赠品","parent_id":212,"perms":"","router":"/200","sort":12,"type":1,"update_at":1653034143,"view_path":""},{"create_at":0,"delete_at":0,"icon":"sc-icon-liushui","id":201,"is_show":1,"keep_alive":1,"name":"会员流水","parent_id":122,"perms":"","router":"/member/finance","sort":10,"type":1,"update_at":1652841795,"view_path":"member/finance.vue"},{"create_at":1635247728,"delete_at":0,"icon":"sc-icon-fenxiao","id":202,"is_show":1,"keep_alive":0,"name":"分销","parent_id":140,"perms":"","router":"","sort":15,"type":0,"update_at":1635248093,"view_path":""},{"create_at":1635248208,"delete_at":0,"icon":"sc-icon-system","id":203,"is_show":1,"keep_alive":1,"name":"分销设置","parent_id":202,"perms":"","router":"/fenxiao/config","sort":9999,"type":1,"update_at":1653034270,"view_path":"fenxiao/config.vue"},{"create_at":1635248922,"delete_at":0,"icon":"sc-icon-fenxiao-order","id":204,"is_show":1,"keep_alive":1,"name":"分销订单","parent_id":202,"perms":"","router":"/fenxiao/order","sort":700,"type":1,"update_at":1653034240,"view_path":"fenxiao/order.vue"},{"create_at":1635248983,"delete_at":0,"icon":"sc-icon-fenxiao-user","id":205,"is_show":1,"keep_alive":1,"name":"分销商","parent_id":202,"perms":"","router":"/fenxiao/user","sort":50,"type":1,"update_at":1653034595,"view_path":"fenxiao/user"},{"create_at":1635249026,"delete_at":0,"icon":"sc-icon-fenxiao-goods","id":206,"is_show":1,"keep_alive":1,"name":"分销商品","parent_id":202,"perms":"","router":"/fenxiao/goods","sort":40,"type":1,"update_at":1655348412,"view_path":"fenxiao/goods"},{"create_at":1635249081,"delete_at":0,"icon":"sc-icon-fenxiao-jiesuan","id":207,"is_show":1,"keep_alive":1,"name":"提现管理","parent_id":202,"perms":"","router":"/fenxiao/withdraw","sort":800,"type":1,"update_at":1653034252,"view_path":"fenxiao/withdraw.vue"},{"create_at":1635249227,"delete_at":0,"icon":"sc-icon-fenxiao-tu","id":208,"is_show":1,"keep_alive":1,"name":"分销概况","parent_id":202,"perms":"","router":"/fenxiao/surveys","sort":10,"type":1,"update_at":1653034159,"view_path":"fenxiao/surveys.vue"},{"create_at":1635528108,"delete_at":0,"icon":"sc-icon-wallet","id":209,"is_show":1,"keep_alive":1,"name":"分销比例设置","parent_id":202,"perms":"","router":"/fenxiao/level","sort":9998,"type":1,"update_at":1653034261,"view_path":"fenxiao/level.vue"},{"create_at":1636428499,"delete_at":0,"icon":"sc-icon-goods","id":210,"is_show":1,"keep_alive":0,"name":"商品","parent_id":135,"perms":"","router":"","sort":60,"type":0,"update_at":1636428611,"view_path":""},{"create_at":1636428573,"delete_at":0,"icon":"sc-icon-ban","id":211,"is_show":1,"keep_alive":1,"name":"商品限购","parent_id":210,"perms":"","router":"/goods/goodsLimit","sort":70,"type":1,"update_at":1662875338,"view_path":"shop/goodsLimit"},{"create_at":1636437218,"delete_at":0,"icon":"sc-icon-activity2","id":212,"is_show":1,"keep_alive":0,"name":"活动","parent_id":140,"perms":"","router":"","sort":11,"type":0,"update_at":1636437231,"view_path":""},{"create_at":1639623870,"delete_at":0,"icon":"sc-icon-monitor","id":216,"is_show":1,"keep_alive":1,"name":"分销商流水","parent_id":202,"perms":"","router":"/fenxiao/user/invoice","sort":60,"type":1,"update_at":1653034227,"view_path":"fenxiao/user/invoice.vue"},{"create_at":1647176519,"delete_at":0,"icon":"el-icon-star","id":217,"is_show":1,"keep_alive":1,"name":"首页","parent_id":1,"perms":"","router":"/dashboard","sort":0,"type":1,"update_at":1650252263,"view_path":"home"},{"create_at":1648364256,"delete_at":0,"icon":"sc-icon-settings","id":218,"is_show":1,"keep_alive":0,"name":"商城设置","parent_id":135,"perms":"","router":"/shop/config","sort":9999,"type":1,"update_at":1650380427,"view_path":"shop/config"},{"create_at":1666185020,"delete_at":0,"icon":"el-icon-setting","id":224,"is_show":1,"keep_alive":0,"name":"拼团设置","parent_id":194,"perms":"","router":"/marketing/tuan/setting","sort":10,"type":1,"update_at":1670080331,"view_path":"marketing/tuan/setting.vue"},{"create_at":1666193217,"delete_at":0,"icon":"sc-icon-menu","id":225,"is_show":1,"keep_alive":0,"name":"拼团列表","parent_id":194,"perms":"","router":"/marketing/tuan/index","sort":0,"type":1,"update_at":1667706073,"view_path":"marketing/tuan/index.vue"},{"create_at":1666193689,"delete_at":0,"icon":"sc-icon-order","id":226,"is_show":1,"keep_alive":0,"name":"场次管理","parent_id":195,"perms":"","router":"/marketing/seckill/setting","sort":10,"type":1,"update_at":1667706176,"view_path":"marketing/seckill/setting.vue"},{"create_at":1666193761,"delete_at":0,"icon":"el-icon-goods","id":227,"is_show":1,"keep_alive":0,"name":"商品管理","parent_id":195,"perms":"","router":"/marketing/seckill/index","sort":0,"type":1,"update_at":1667706145,"view_path":"marketing/seckill/index.vue"},{"create_at":1666194084,"delete_at":0,"icon":"sc-icon-coupon","id":228,"is_show":1,"keep_alive":0,"name":"组合套餐","parent_id":140,"perms":"","router":"/marketing/bundling","sort":11,"type":1,"update_at":1666194130,"view_path":"marketing/bundling"}],"perms":[]}}
	if (menu.code === 0) {
		// 处理菜单
		const routes = menu.data.menus.filter(e => e.type !== 2).map(e => {
			return {
				id: e.id,
				parentId: e.parent_id,
				path: tool.revisePath(e.router || String(e.id)),
				component: e.view_path,
				type: e.type,
				// name: e.name,
				name: tool.transformName(e.router),
				icon: e.icon,
				orderNum: e.sort,
				isShow: tool.isEmpty(e.is_show) ? true : e.is_show,
				meta: {
					title: e.name,
					icon: e.icon,
					keepAlive: e.keep_alive,
					hidden: e.is_show === 1 ? 0 : 1,
					affix: e.router === '/dashboard' ? 1 : 0,
				},
				children: []
			};
		})
		if (routes.length < 1) {
			return [false, '当前用户无任何菜单权限，请联系系统管理员']
		}
		// const menuGroup = tool.deepTree(routes);
		const menuGroup = tool.deepTreeOrder(routes,"parentId","id","children",
			(a,b)=>b.orderNum-a.orderNum);
		tool.data.setMenu(menuGroup)
		tool.data.setPermissions(menu.data.perms)

		return [true, '获取成功']
	} else {
		return [false, menu.message]
	}
};

tool.getBaseUrl = async function (apiObj) {
	let tmp = tool.data.get("BASE_URL") || "";
	if (tmp) {
		return tmp;
	}
	let res = await apiObj.gdshop.attachment.getBaseUrl()
	if (res.code === 0) {
		tool.data.set("BASE_URL", res.data.base_url);
		return res.data.base_url;
	} else {
		return ''
	}
}

tool.getNumber = (value) => {
	const toFixedNum = Number(value).toFixed(3);
	return value ? toFixedNum.substring(0, toFixedNum.toString().length - 1) : "0.00";
};

tool.getMoneyByMinute = (value) => {
	return tool.getNumber(value / 100);
};

tool.get10KMoneyByMinute = (value) => {
	if (value > 1000000) {
		return tool.getNumber(value / 1000000) + "万";
	} else {
		return tool.getNumber(value / 100);
	}
}


/**
 * 笛卡尔积算法
 * @param array
 * @returns {*|*[]|U}
 */
tool.descartes = (array) => {
	if (array.length < 2) {
		return array[0] || [];
	}

	return [].reduce.call(array, (col, set) => {
		const res = [];
		col.forEach((c) => {
			set.forEach((s) => {
				const t = [].concat(Array.isArray(c) ? c : [c]);
				t.push(s);
				res.push(t);
			});
		});

		return res;
	});
};
/**
 * 生成随机字符串
 */
tool.createUniqueString = () => {
	const timestamp = +new Date() + "";
	const randomNum = parseInt((1 + Math.random()) * 65536) + "";
	return (+(randomNum + timestamp)).toString(32);
};

/**
 * 数组去重
 * @param {Array} arr
 * @returns {Array}
 */
tool.uniqueArr = (arr) => {
	return Array.from(new Set(arr));
};

/**
 * @param {Array} arr1
 * @param {Array} arr2
 * @returns {Array}
 */
tool.diffArary = (arr1, arr2) => {
	arr1 = tool.uniqueArr(arr1);
	arr2 = tool.uniqueArr(arr2);
	return arr1.concat(arr2).filter((arg) => !(arr1.includes(arg) && arr2.includes(arg)));
};

tool.arrayUnique = (arr, _key) => {
	const obj = {};
	return arr.reduce(function (item, next) {
		obj[next[_key]] ? "" : (obj[next[_key]] = true && item.push(next));
		return item;
	}, []);
};

tool.sku = {}
// 计算每个sku后面有多少项
tool.sku.getLevels = (tree) => {
	let level = [];
	for (let i = tree.length - 1; i >= 0; i--) {
		if (tree[i + 1] && tree[i + 1].leaf) {
			level[i] = tree[i + 1].leaf.length * level[i + 1] || 1;
		} else {
			level[i] = 1;
		}
	}
	return level;
}
// 笛卡尔积运算
tool.sku.flatten = (tree, stocks = [], options) => {
	let { optionValue = "id", optionText = "value" } = options || {};
	let result = [];
	let skuLen = 0;
	let stockMap = {}; // 记录已存在的stock的数据
	const level = tool.sku.getLevels(tree);
	if (tree.length === 0) return result;
	tree.forEach((sku) => {
		const { leaf } = sku;
		if (!leaf || leaf.length === 0) return true;
		skuLen = (skuLen || 1) * leaf.length;
	});
	// 根据已有的stocks生成一个map
	stocks.forEach((stock) => {
		let { skus, ...attr } = stock;
		stockMap[skus.map((item) => `${item.k_id}_${item.v_id}`).join("|")] = attr;
	});
	for (let i = 0; i < skuLen; i++) {
		let skus = [];
		let mapKey = [];
		tree.forEach((sku, column) => {
			const { leaf } = sku;
			let item = {};
			if (!leaf || leaf.length === 0) return true;
			if (leaf.length > 1) {
				let row = parseInt(i / level[column], 10) % leaf.length;
				item = tree[column].leaf[row];
			} else {
				item = tree[column].leaf[0];
			}
			if (!sku[optionValue] || !item[optionValue]) return;
			mapKey.push(`${sku[optionValue]}_${item[optionValue]}`);
			skus.push({
				k_id: sku[optionValue],
				k: sku[optionText],
				v_id: item[optionValue],
				v: item[optionText]
			});
		});
		let { ...data } = stockMap[mapKey.join("|")] || {};
		// 从map中找出存在的sku并保留其值
		result.push({ ...data, skus });
	}
	return result;
};
// 判断两个sku是否相同
tool.sku.isEqual = (prevSKU, nextSKU, options) => {
	let { optionValue = "id" } = options || {};
	return (
		nextSKU.length === prevSKU.length &&
		nextSKU.every(({ leaf = [] }, index) => {
			let prevLeaf = prevSKU[index].leaf || [];
			return (
				prevSKU[index][optionValue] === nextSKU[index][optionValue] &&
				leaf.length === prevLeaf.length &&
				leaf.map((item) => item[optionValue]).join(",") ===
				prevLeaf.map((item) => item[optionValue]).join(",")
			);
		})
	);
}

tool.getStatusText = (_status) => {
	if (!_status && _status !== 0) return "";
	_status = _status.toString();
	switch (_status) {
		case "0":
			return "关闭";
		case "1":
			return "待付款";
		case "2":
			return "待备货";
		case "3":
			return "待发货";
		case "4":
			return "待收货";
		case "5":
			return "待评价";
		case "99":
			return "已完成";
	}
	return "";
}
tool.isOrderShowBtn = (_type, _order) => {
	if (!_order.subs) {
		return false;
	}
	if (_type === "close_order") {
		// 如果子订单有售后，不显示关闭订单 按钮
		const tmp = _order.subs.filter((item) => {
			return item.refund_status > 0;
		});
		if (tmp.length > 0) {
			return false;
		}
		return _order.status > 0 && _order.status < 4;
	} else if (_type === "confirm_goods") {
		return _order.status == 2;
	} else if (_type === "send_order") {
		return _order.status == 3;
	} else if (_type === "confirm_order") {
		return _order.status == 4;
	} else {
		return false;
	}
}

export default tool
